package com.csj.lc.conf;

import com.csj.lc.entity.User;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class MyInterceptor implements HandlerInterceptor {
    long start = System.currentTimeMillis();

    //请求执行前运行
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {

        User loginUser = (User)request.getSession().getAttribute("loginUser");
        if(loginUser == null){

            // 0.使用这个方法可以传递信息
            // request.getSession().setAttribute("msg","没有用户!");

            // 1.使用重定向 : 比较难携带信息
//            response.sendRedirect("/lc/index");

            // 2. 使用转发： url会仍然是旧的
            request.getRequestDispatcher("index").forward(request,response);

            return false;
        }else{
            return true;
        }

    }

    //请求结束后运行
    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

//        System.out.println( "HtmlInterceptor.postHandle");
//        System.out.println("Interceptor cost="+(System.currentTimeMillis()-start));
    }

    //视图渲染完成后才执行
    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

//        System.out.println( "HtmlInterceptor.afterCompletion");
    }
}
